<template>
  <div class="cart">
    <el-card header="服务清单">
      <el-table empty-text="您还没有呢~" :data="cartList" v-if="cartList.length>0" @select="handleSelect"
                @selection-change="handleSelectChange" ref="cartTableRef">
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="编号" align="center" prop="id"/>
        <el-table-column label="图片" align="center" prop="pic" :show-overflow-tooltip="true">
          <template #default="{row}">
            <span v-if="row.pic===''">暂无</span>
            <el-image v-else :src="row.pic" style="width: 60px; height: 60px" fit="fill"
                      :preview-src-list="[row.pic]"/>
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center" prop="name"/>
        <el-table-column label="价格" align="center" prop="price">
          <template #default="{row}">
            <span style="color: red;font-weight: bolder">￥{{ Number(row.price).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="可获得积分" align="center" prop="point"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="{row}">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="removeCart(row)">移出
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页插件-->
      <el-empty v-else description="您还没有呢~">
        <slot>
          <m-button text="去选购" @click="toCart()" classStyle="main-btn"></m-button>
        </slot>
      </el-empty>
    </el-card>
    <el-card v-if="cartList.length>0">
      <el-row>
        <el-col :span="12"></el-col>
        <el-col :span="3">
          <el-row class="ub cross-center" style="text-align: center">
            <el-col>已选择 <span class="cart-font">{{ totalSelected }}</span> 套服务
            </el-col>
            <el-col style="color: gray;font-size: small;margin-top: 10px">共计 <span> {{ cartList.length }} </span> 套服务
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="4">
          <el-row class="ub main-justify">
            <el-col :span="4"></el-col>
            <el-col :span="20">应付总额:<span class="cart-font"> ¥ {{ Number(totalAmount).toFixed(2) }}</span></el-col>
          </el-row>
        </el-col>
        <el-col :span="3">
          <el-row>
            <el-col :span="20"></el-col>
            <el-col :span="4">
              <!--              disabled-btn-->
              <m-button style="width: 160px;height: 50px;line-height: 50px;font-size: 16px"
                        text="去结算"
                        @click="toCheckOut()" :classStyle="totalSelected>0?'main-btn':'disabled-btn'"></m-button>
            </el-col>
          </el-row>

        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import { computed, onMounted, ref, nextTick, watch, reactive, toRefs, inject } from 'vue'
import { useStore } from 'vuex'
import MButton from '../../components/MButton.vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import cartItemApi from '../../api/cartItem'
import { getToken } from '../../utils/auth'

export default {
  name: 'index',
  components: { MButton },
  setup () {
    const store = useStore()
    const router = useRouter()
    const state = reactive({
      // 选择的商品
      selectionList: [],
    })
    const cartTableRef = ref(null)
    // console.log(reload)
    let cartList = store.getters.cartList
    // console.log(cartList)

    ///----------计算属性 start
    // 计算总价格
    const totalAmount = computed(() => {
      let total = 0
      state.selectionList.forEach(e => {
        total += e.price
      })
      return total
    })
    // 计算选中个数
    const totalSelected = computed(() => {
      let total = 0
      state.selectionList.forEach(e => {
        if (e.checked) {
          total += 1
        }
      })
      return total
    })

    ///----------计算属性 end

    //-------------- 方法 start

    // 从购物车移除
    const removeCart = (product) => {
      if (product.checked) {
        ElMessageBox.confirm('确定要移除吗~', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (getToken()) {
            cartItemApi.removeCart(product.id)
            // 页面又换存 只能这样解决 目前
          } else {
            store.commit('REMOVE_CART', product)
          }
          router.push('/home')
        }).catch(error => {
          ElMessage.warning('取消成功')
        })
      } else {
        store.commit('REMOVE_CART', product)
      }
      // router.go(0)
    }
    // 去选购
    const toCart = () => {
      router.push('/home')
    }
    // 手动勾选
    const handleSelect = (selection, row) => {
      store.commit('CHANGE_CHECKED', { productId: row.id, checked: !row.checked })
    }
    // 处理商品选择变化
    const handleSelectChange = (selection) => {
      state.selectionList = [...selection]
    }
    // 去结算
    const toCheckOut = () => {
      router.push('/checkout')
    }
    //-------------- 方法 end

    nextTick(() => {
      if (cartList.length) {
        cartList.forEach(e => {
          if (e.checked) {
            cartTableRef.value.toggleRowSelection(e, true)
          }
        })
      }
    })

    // watch监听
    // watch(() => state.selectionList, (newVal, oldVal) => {
    // }, { deep: true, immediate: true })
    onMounted(() => {

    })
    return {
      cartList,
      totalAmount,
      totalSelected,
      cartTableRef,
      ...toRefs(state),
      toCheckOut,
      removeCart,
      handleSelect,
      handleSelectChange,
      toCart
    }
  },
}
</script>

<style scoped lang="scss">
.cart-font {
  color: red;
  font-weight: bolder;
  font-size: 15px;
}
</style>
`
